package com.yfqy.app.modules.order.context;

import io.netty.util.concurrent.FastThreadLocal;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * 订单上下文
 */
@Data
public class OrderBuilderContext {

    private static final FastThreadLocal<Map<Object, Object>> orderBuilderContext = new FastThreadLocal<Map<Object, Object>>() {
        @Override
        protected Map<Object, Object> initialValue() {
            return new HashMap<Object, Object>();
        }

    };

    /**
     * 根据key获取值
     *
     * @param key
     * @return
     */
    public static Object getValue(Object key) {
        if (orderBuilderContext.get() == null) {
            return null;
        }
        return orderBuilderContext.get().get(key);
    }

    /**
     * 存储
     *
     * @param key
     * @param value
     */
    public static void setValue(Object key, Object value) {
        Map<Object, Object> cacheMap = orderBuilderContext.get();
        if (cacheMap == null) {
            cacheMap = new HashMap<Object, Object>();
            orderBuilderContext.set(cacheMap);
        }
        cacheMap.put(key, value);
    }

    /**
     * 根据key移除值
     *
     * @param key
     */
    public static void removeValue(Object key) {
        Map<Object, Object> cacheMap = orderBuilderContext.get();
        if (cacheMap != null) {
            cacheMap.remove(key);
        }
    }

    /**
     * 重置
     */
    public static void reset() {
        if (orderBuilderContext.get() != null) {
            orderBuilderContext.get().clear();
        }
        orderBuilderContext.remove();
    }

}
